<template>
    <div class="mytab-bg">
        <a
            href="javascript:;"
            class="swiperArrow"
            v-if="isSwiperArrowLeft"
            @click="swiperGoPosition(200)"
        >
            <i class="el-icon-arrow-left"></i>
        </a>
        <div class="mytab" ref="mytabBox">
            <swiper :options="swiperOption" ref="mySwiper">
                <swiper-slide
                    class="swiper-no-swiping"
                    :style="{width:swiperWidth + 'px'}"
                    ref="swiperSlide"
                >
                    <ul ref="swiperBody">
                        <li
                            v-for="item in mytab"
                            :key="item.id"
                            :class="{current: $route.name + $route.path === item.id || item.model + $route.path === item.id}"
                            @contextmenu.prevent="showRightHandMenu($event,item)"
                            @dblclick.prevent.stop="closeThis(item)"
                        >
                            <router-link href="javascript:;" :to="item.path">{{item.name}}</router-link>
                            <span @click="closeThis(item)" v-if="item.id !== 'home/'" title="关闭页签">
                                <i class="el-icon-close"></i>
                            </span>
                        </li>
                    </ul>
                </swiper-slide>
            </swiper>
            <context-menu :buttons="buttons" ref="contextMenu">右键菜单</context-menu>
        </div>
        <a
            href="javascript:;"
            class="swiperArrow"
            v-if="isSwiperArrowRight"
            @click="swiperGoPosition(-200)"
        >
            <i class="el-icon-arrow-right"></i>
        </a>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import 'swiper/dist/css/swiper.css';
import { swiper, swiperSlide } from 'vue-awesome-swiper';

export default {
    name: 'myTab',

    components: {
        swiper,
        swiperSlide
    },

    data() {
        let that = this;
        let timer;

        return {
            currentTab: {},
            swiperOption: {
                direction: 'horizontal',
                slidesPerView: 'auto',
                freeMode: true,
                mousewheel: true,
                noSwiping: true,
                on: {
                    setTranslate() {
                        clearTimeout(timer);
                        timer = setTimeout(() => {
                            that.resetArrow();
                        }, 300);
                    }
                }
            },
            swiperWidth: 0,
            isSwiperArrowLeft: false,
            isSwiperArrowRight: false
        };
    },

    computed: {
        ...mapState('mytab', ['mytab']),

        swiper() {
            return this.$refs.mySwiper.swiper;
        },

        buttons() {
            return [
                {
                    name: '关闭',
                    icon: 'el-icon-close',
                    isHidden: false,
                    callback: () => {
                        this.closeThisTab();
                    }
                },
                {
                    name: '除此之外全部关闭',
                    icon: 'el-icon-error',
                    isHidden: false,
                    callback: () => {
                        this.closeOtherTab();
                    }
                },
                {
                    name: '关闭左侧页签',
                    icon: 'el-icon-error',
                    isHidden: false,
                    callback: () => {
                        this.closeLeftTab();
                    }
                },
                {
                    name: '关闭右侧页签',
                    icon: 'el-icon-error',
                    isHidden: false,
                    callback: () => {
                        this.closeRightTab();
                    }
                }
            ];
        }
    },

    watch: {
        mytab() {
            this.$nextTick(function() {
                this.resetSwiperWidth();
            });
        }
    },

    mounted() {
        this.resetSwiperWidth();
    },

    methods: {
        // 重新计算tab整体宽度
        resetSwiperWidth() {
            this.swiperWidth = this.$refs.swiperBody.offsetWidth;

            // 计算并设置滚动到当前标签位置
            // 全长滚动节点
            let innerElem = this.$refs.swiperSlide.$el;
            // 滚动父节点，可设置滚动
            let parentElem = innerElem.parentNode;
            // 标签集合
            let items = innerElem.childNodes[0].childNodes;
            // 当前标签
            let currentEl = '';
            // 当前滚动过的距离
            let transformLeft = this.swiper.getTranslate();
            // 获取当前页签元素
            let i = 0;
            for (; i < items.length; i++) {
                if (items[i].className.indexOf('current') > -1) {
                    currentEl = items[i];
                }
            }

            // 处理前半部分被遮挡的移动【100代表多移动的距离，表示前面还有东西】
            if (currentEl.offsetLeft < -transformLeft) {
                let beforeLeft = currentEl.offsetLeft - 100;
                if (beforeLeft < 0) {
                    beforeLeft = 0;
                }
                this.$nextTick(function() {
                    this.swiper.setTransition(300);
                    console.log('beforeLeft', beforeLeft);
                    this.swiper.setTranslate(-beforeLeft);
                });
            }
            // 处理后半部分被遮挡的移动【100代表多移动的距离，表示后面还有东西】
            if (currentEl.offsetLeft + currentEl.offsetWidth > parentElem.offsetWidth + -transformLeft) {
                let afterLeft = currentEl.offsetLeft + currentEl.offsetWidth - parentElem.offsetWidth;
                // 10为当前页签在css中定义的margin-right:10px;
                if (afterLeft + parentElem.offsetWidth + 10 < innerElem.offsetWidth) {
                    afterLeft += 100;
                }
                this.$nextTick(function() {
                    this.swiper.setTransition(300);
                    this.swiper.setTranslate(-afterLeft);
                });
            }

            // 计算是否显示左右箭头
            // 左箭头【400好秒延迟是应为有滚动的动画时间】
            // setTimeout(() => {
            //     this.resetArrow()
            // }, 400)
        },
        // 渲染箭头数据
        resetArrow() {
            // this.swiper不存在时不做处理
            if (this.swiper.destroyed) {
                return false;
            }
            // 当前滚动过的距离
            let transformLeft = this.swiper.getTranslate();
            // 全长滚动节点
            let innerElem = this.$refs.swiperSlide.$el;
            // 滚动父节点，可设置滚动
            let parentElem = innerElem.parentNode;
            if (transformLeft < 0) {
                this.isSwiperArrowLeft = true;
            } else {
                this.isSwiperArrowLeft = false;
            }
            // 右箭头
            if (innerElem.offsetWidth + transformLeft - 5 > parentElem.offsetWidth) {
                this.isSwiperArrowRight = true;
            } else {
                this.isSwiperArrowRight = false;
            }
        },
        // 根据当前位置去加减位置
        swiperGoPosition(count) {
            // 当前滚动过的距离
            let transformLeft = this.swiper.getTranslate();
            this.swiper.setTransition(300);
            this.swiper.setTranslate(transformLeft + count);
        },
        // 显示右键菜单
        showRightHandMenu(event, item) {
            this.currentTab = item;
            this.$refs.contextMenu.show(event, this.$el);
        },
        // 在新的页签中打开
        openNewPage() {
            window.open('#' + this.currentTab.path);
        },
        closeThis(item) {
            this.$multRun.store.del(item.path);
            this.$mytab.del(item.id);
        },
        // 关闭当前右键页签
        closeThisTab() {
            this.$multRun.store.del(this.currentTab.path);
            this.$mytab.del(this.currentTab.id);
        },
        // 关闭其他页签
        closeOtherTab() {
            let tabs = [];
            let thisID = this.currentTab.id;
            this.$mytab.get().map(v => {
                if (v.id !== thisID) {
                    this.$multRun.store.del(v.path);
                    tabs.push(v.id);
                }
            });
            tabs.map(v => {
                this.$mytab.del(v);
            });
        },
        // 关闭左侧页签
        closeLeftTab() {
            let tabs = [];
            let thisID = this.currentTab.id;
            let flag = false;
            this.$mytab.get().map(v => {
                if (v.id === thisID) {
                    flag = true;
                }
                if (!flag) {
                    this.$multRun.store.del(v.path);
                    tabs.push(v.id);
                }
            });
            tabs.map(v => {
                this.$mytab.del(v);
            });
        },
        // 关闭右侧页签
        closeRightTab() {
            let tabs = [];
            let thisID = this.currentTab.id;
            let flag = false;
            this.$mytab.get().map(v => {
                if (flag) {
                    this.$multRun.store.del(v.path);
                    tabs.push(v.id);
                }
                if (v.id === thisID) {
                    flag = true;
                }
            });
            tabs.map(v => {
                this.$mytab.del(v);
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.mytab {
    user-select: none;
    line-height: 30px;
    margin: 0 20px;
    overflow: hidden;
    li {
        display: inline-block;
        margin: 0 5px;
        position: relative;
        border: 1px solid #ebebeb;
        border-bottom: 0;
        border-radius: 5px 5px 0 0;
        height: 31px;
        overflow: hidden;
        &.current {
            border-color: #ebebeb;
            background: #d6dde3;
            a {
                background: #d6dde3 !important;
            }
            &:hover {
                border-color: #ebebeb;
            }
        }
        &:hover {
            border-color: #c6e2ff;
            a {
                background: #ecf5ff;
            }
        }
        a {
            display: block;
            background: #fff;
            padding: 0 20px;
            color: #333;
            font-size: 14px;
        }
        span {
            position: absolute;
            right: 1px;
            top: 1px;
            width: 14px;
            height: 14px;
            line-height: 14px;
            font-size: 10px;
            cursor: pointer;
            border-radius: 50px;
            text-align: center;
            &:hover {
                background: #dd4738;
                color: #fff;
            }
        }
    }
    .swiper-slide {
        & > ul {
            padding: 0;
            list-style: none;
            height: 31px;
            white-space: nowrap;
            float: left;
            margin: 0;
        }
        &.text {
            padding: 0;
        }
    }
}
.mytab-bg {
    background: #fafafa;
    padding: 6px 0 0 0;
    position: relative;
}
.swiperArrow {
    border: 1px solid #ebebeb;
    height: 31px;
    border-bottom: 0;
    position: absolute;
    bottom: 0;
    line-height: 28px;
    color: #5a5e66;
    background: #fff;
    &:hover {
        border-color: #c6e2ff;
        background: #ecf5ff;
    }
    &:first-child {
        left: 0;
        border-radius: 0 3px 0 0;
    }
    &:last-child {
        right: 0;
        border-radius: 3px 0 0 0;
    }
}
</style>
